# 引入selenium库中的webdriver模块，实现对网页的操作
from selenium import webdriver
# 引入time模块，实现延时
import time
# 引入By Class,辅助元素定位
from selenium.webdriver.common.by import By
# 引入ActionChains Class, 辅助鼠标移动、
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec


# 防止浏览器自动关闭
# option = webdriver.EdgeOptions()
# option.add_experimental_option("detach", True)

def login():
    # 打开浏览器
    driver = webdriver.Edge()

    # 打开网页
    driver.get("http:/saas.51learning.com.cn/listen/loginnchu.html")

    # 全屏展示
    driver.maximize_window()

    # 输入账号密码
    driver.find_element(By.XPATH,'//*[@id="user"]').send_keys('23201422')
    driver.find_element(By.XPATH, '//*[@id="pwd"]').send_keys('147258369h.')

    # 点击登录
    WebDriverWait(driver, 5, 0.5).until(ec.visibility_of_element_located((By.XPATH, '/html/body/div[1]/div/div/div/div/div/button[1]')))
    driver.find_element(By.XPATH, '/html/body/div[1]/div/div/div/div/div/button[1]').click()

    # 点击大学生听力提高级
    WebDriverWait(driver, 5, 0.5).until(ec.presence_of_element_located((By.XPATH, '//*[@id="iframepage"]')))
    iframe_label = driver.find_element(By.XPATH, '//*[@id="iframepage"]')
    driver.switch_to.frame(iframe_label)
    WebDriverWait(driver, 5, 0.5).until(ec.presence_of_element_located((By.XPATH, '//*[@id="div_book"]/div[2]/div[1]/div[1]/a[2]')))
    driver.find_element(By.XPATH, '//*[@id="div_book"]/div[2]/div[1]/div[1]/a[2]').click()

    # 点击第一单元的学习
    WebDriverWait(driver, 5, 0.5).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="unit52"]/div[3]/button[2]')))
    driver.find_element(By.XPATH, '//*[@id="unit52"]/div[3]/button[2]').click()

    # 开始

    # c1p2
    WebDriverWait(driver, 5, 0.5).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="chapter_menu1"]/li[2]/a')))
    driver.find_element(By.XPATH, '//*[@id="chapter_menu1"]/li[2]/a').click()

    # 读取答案并填入
    file_name ='D:\python文件\英语听力答案.txt'
    with open(file_name) as file_object:
        lines = file_object.readlines()
        driver.find_element(By.XPATH, '//*[@id="1"]').send_keys(lines[0])
        driver.find_element(By.XPATH, '//*[@id="2"]').send_keys(lines[1])
        driver.find_element(By.XPATH, '//*[@id="3"]').send_keys(lines[2])

    # c2t1n1
    WebDriverWait(driver, 5, 0.5).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="chapter131"]')))
    driver.find_element(By.XPATH, '//*[@id="chapter131"]').click()


login()
time.sleep(5)